﻿@model Windshield.ViewModels.BoardViewModel

<div class ="row-fluid">
	<table id="tic-tac-toe" class="table-bordered cursor-pointer">
		<tbody>
			<tr>
				<td id="cell0"></td>
				<td id="cell1"></td>
				<td id="cell2"></td>
			</tr>
			<tr>
				<td id="cell3"></td>
				<td id="cell4"></td>
				<td id="cell5"></td>
			</tr>
			<tr>
				<td id="cell6"></td>
				<td id="cell7"></td>
				<td id="cell8"></td>
			</tr>
		</tbody>
	</table>
</div>
<hr>
<div class="row-fluid">
	<div id="game-win" class="alert alert-success span2 offset3 text-center">0</div>
	<div id="game-draw" class="alert alert-warning span2 text-center">0</div>
	<div id="game-loss" class="alert alert-error span2 text-center">0</div>
</div>
<div class="row-fluid">
	<div id="popup" class="span6 offset3 alert alert-info text-center">

	</div>
</div>
<div class="row-fluid text-center">
	<input type="button" id="game-restart" class="btn" value="Restart" />
</div>

<script>
	$(document).ready(function () {
		var group = '@(Model.id)';
		var hub = $.connection.gameHub;
		var currentUser = '@(Context.User.Identity.Name)';
		var players = '@Model.GetPlayers(2)';
		var playerOne = '@Model.GetPlayers(1)[0].UserName';
		var playerTwo = '@Model.GetPlayers(2)[1].UserName';
		
		$("#game-restart").hide();

		hub.client.Broadcast = function (status) {
			for (var i=0; i<9; i++)
			{
				$("#cell" + i).text(status[i]);
			}

			var statusArray = status.split("|");

			if (currentUser == playerOne) {
				$("#game-win").text(statusArray[3]);
				$("#game-draw").text(statusArray[4]);
				$("#game-loss").text(statusArray[5]);
			}
			else {
				$("#game-win").text(statusArray[5]);
				$("#game-draw").text(statusArray[4]);
				$("#game-loss").text(statusArray[3]);
			}
		};

		hub.client.GameOver = function (winner) {
			if (winner != "") {
				$("#popup").text(winner + " wins!");
				if (winner == currentUser) {
					$("#game-win").html(parseInt($("#game-win").html(), 10) + 1);
				}
				else {
					$("#game-loss").html(parseInt($("#game-loss").html(), 10) + 1);
				}
			}
			else {
				$("#popup").text("It's a draw!");
				$("#game-draw").html(parseInt($("#game-draw").html(), 10) + 1);
			}

			$("#game-restart").show();
		}

		$.connection.hub.start().done(function () {
			hub.server.join(group);
			hub.server.startGame(group);
			hub.server.tryAction(group, "checkAI", currentUser);

			$("#tic-tac-toe tr td").click(function () {
				hub.server.tryAction(group, "insert" + this.id, currentUser);
			});

			$("#game-restart").click(function () {
				hub.server.tryAction(group, "checkAI", currentUser);
				//setTimeout(function () { hub.server.refresh(group); }, 1250);
				$("#game-restart").hide();
			});
		});
	});

</script>